import os
import shutil
import subprocess
import time
import glob
import mypyutils.virtualenv
import mypyutils.compression

ORDER_CFG = '__order__.cfg'

def setup_requirements(requirementsDir, virtualenvDir, tempDir, packageExtensions):
	"""
	packageExtensions is a string with the extensions separated by a semicolon
	"""
	
	def install_package(packagePath, virtualenvDir, tempDir):
		if not os.path.isfile(packagePath):
			raise Exception('Package path is not a file: ' + packagePath)
		if not os.path.isdir(virtualenvDir):
			raise Exception('Virtual environment directory not found: ' + virtualenvDir)
		if not os.path.isdir(tempDir):
			raise Exception('Temporary directory not found: ' + tempDir)
		packageName = os.path.basename(packagePath)
		print 'Installing: ', packageName + '...'
		packageTempDir = os.path.join(tempDir, packageName)
		mypyutils.compression.extract(packagePath, packageTempDir)
		dirEntries = os.listdir(packageTempDir)
		if (len(dirEntries)) == 0:
			raise Exception('No child directory found after unpacking: ' + packageName)
		if len(dirEntries) > 1:
			raise Exception('More than one child directory found after unpacking: ' + packageName)
		setupDir = os.path.join(packageTempDir, dirEntries[0])
		callerDir = os.getcwd()
		try:
			os.chdir(setupDir)
			time.sleep(0.05)

			pythonExe = os.path.join(virtualenvDir, mypyutils.virtualenv.PYTHON_EXE)
			if not os.path.isfile(pythonExe):
				raise Exception('Invalid python executable path: ' + pythonExe)
			if not os.path.isfile('setup.py'):
				raise Exception('setup.py not found in: ' + setupDir)
	
			subprocess.call([pythonExe, 'setup.py', 'install'])		
			#if result:
			#	raise Exception(result + '\nError Code: ' + str(proc.returncode))
		finally:
			os.chdir(callerDir)
		time.sleep(0.05)
	
	def del_temp_dir(tempDir):
		print 'Deleting temp directory: ', tempDir
		time.sleep(0.2)
		shutil.rmtree(tempDir, ignore_errors=True)
		time.sleep(0.2)
	
	print 'Setting up requirements...'
	del_temp_dir(tempDir)
	try:
		os.makedirs(tempDir)
		orderCfgFileName = os.path.join(requirementsDir, ORDER_CFG)
		if os.path.isfile(orderCfgFileName):
			with open(orderCfgFileName) as orderCfgFile:
				for line in orderCfgFile:
					line = line.strip()
					if not line or line.startswith('#'):
						print line
					else:
						searchString = os.path.join(requirementsDir, line + '.*')
						packagePaths = glob.glob(searchString)
						if len(packagePaths) == 1:
							install_package(packagePaths[0], virtualenvDir, tempDir)
						else:
							print 'Error: ', len(packagePaths), ' files found for ', searchString, '. Ignoring package.'
		else:
			for extension in packageExtensions.split(';'):
				for packagePath in glob.iglob(os.path.join(requirementsDir, extension)):
					install_package(packagePath, virtualenvDir, tempDir)
	finally:
		del_temp_dir(tempDir)
